package com.gubei.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.gubei.subject.domain.convert.SubjectCategoryConverter;
import com.gubei.subject.domain.convert.SubjectLabelConverter;
import com.gubei.subject.domain.entity.SubjectCategoryBO;
import com.gubei.subject.domain.entity.SubjectLabelBO;
import com.gubei.subject.domain.service.SubjectCategoryDomainService;
import com.gubei.subject.domain.util.CacheUtil;
import com.gubei.subject.infra.basic.entity.SubjectCategory;
import com.gubei.subject.infra.basic.entity.SubjectLabel;
import com.gubei.subject.infra.basic.entity.SubjectMapping;
import com.gubei.subject.infra.basic.service.SubjectCategoryService;
import com.gubei.subject.common.enums.IsDeletedFlagEnum;
import com.gubei.subject.infra.basic.service.SubjectLabelService;
import com.gubei.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public boolean add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        int count = subjectCategoryService.insert(subjectCategory);
        return count > 0;
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategory.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOList =SubjectCategoryConverter.INSTANCE.convertCategoryListToCategoryBoList(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategory.subjectCategoryBOList:{}", JSON.toJSONString(subjectCategoryBOList));
        }
        //各分類における題目数を探す
        subjectCategoryBOList.forEach(bo -> {
           Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
           bo.setCount(subjectCount);
        });

        return subjectCategoryBOList;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List<SubjectCategoryBO> subjectCategoryBoList = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBolist(id));
        return subjectCategoryBoList;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBolist(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategoryAndLabel.getSubjectCategoryBolist.subjectCategoryList:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> subjectCategoryBOList =SubjectCategoryConverter.INSTANCE.convertCategoryListToCategoryBoList(subjectCategoryList);
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long,List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBoList(category),threadPoolExecutor)
        ).collect(Collectors.toList());
        completableFutureList.forEach(future -> {
            try{
                Map<Long,List<SubjectLabelBO>> resultMap = future.get();
                if(!MapUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        });
        subjectCategoryBOList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        subjectCategoryBOList.forEach(subjectCategoryBO -> {
            if(!CollectionUtils.isEmpty(map.get(subjectCategoryBO.getId()))) {
                subjectCategoryBO.setLabelBOList(map.get(subjectCategoryBO.getId()));
            }
        });

        return subjectCategoryBOList;
    }

    private Map<Long,List<SubjectLabelBO>> getLabelBoList(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryController.queryCategoryAndLabel.getLabelBoList.subjectCategoryBO:{}", JSON.toJSONString(subjectCategoryBO));
        }
        Map<Long,List<SubjectLabelBO>> labelBoMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(subjectCategoryBO.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        if(CollectionUtils.isEmpty(subjectMappingList)){
            return null;
        }
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> subjectLabelBOList = new LinkedList<>();
        subjectLabelList.forEach(subjectLabel -> {
//            SubjectLabelBO subjectLabelBO = SubjectLabelConverter.INSTANCE.convertLabelToLabelBO(subjectLabel);
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(subjectLabel.getId());
            subjectLabelBO.setLabelName(subjectLabel.getLabelName());
            subjectLabelBO.setCategoryId(subjectLabel.getCategoryId());
            subjectLabelBO.setSortNum(subjectLabel.getSortNum());
            subjectLabelBOList.add(subjectLabelBO);
        });

        //Stream流
        List<SubjectLabelBO> labelBOList = subjectLabelList.stream().map(subjectLabel -> {
//            SubjectLabelBO subjectLabelBO = SubjectLabelConverter.INSTANCE.convertLabelToLabelBO(subjectLabel);
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(subjectLabel.getId());
            subjectLabelBO.setCategoryId(subjectLabel.getCategoryId());
            subjectLabelBO.setLabelName(subjectLabel.getLabelName());
            subjectLabelBO.setSortNum(subjectLabel.getSortNum());
            return subjectLabelBO;
        }).collect(Collectors.toList());

        labelBoMap.put(subjectCategoryBO.getId(), labelBOList);
        return labelBoMap;
    }
}
